<?php


namespace app\common\lib\sms;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\common\exception\LogicException;
use think\Exception;
use think\facade\Config;

class AliSms implements Sms
{

    /**
     * @param $mobile
     * @param $templateCode
     * @param  array  $templateParam
     * @return bool
     * @throws \Exception
     *
     * @Author: Li Guo Xin <guoxinlee129@gmail.com>
     * @Date: 2020/5/8
     * @Time: 19:19
     */
    public static function send($mobile, $templateCode, $templateParam)
    {
        // TODO: Implement send() method.
        try {
            AlibabaCloud::accessKeyClient(Config::get('system.ali_sms.access_key_id'),
                Config::get('system.ali_sms.access_key_secret'))
                ->regionId('cn-hangzhou')
                ->asDefaultClient();

            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId'      => 'cn-hangzhou',
                        'PhoneNumbers'  => $mobile,
                        'SignName'      => '意在笑',
                        'TemplateCode'  => $templateCode,
                        'TemplateParam' => json_encode($templateParam),
                    ],
                ])
                ->request();

            $resultArr = $result->toArray();
            if ($resultArr['Message'] === 'OK' && $resultArr['Code'] === 'OK') {
                return true;
            }
            throw new LogicException(['msg' => '发送失败！', 'data' => $resultArr]);
        } catch (\Exception $exception) {
            //var_dump($exception->getMessage());die;
            throw $exception;
        }
    }

    public static function multiSend(array $mobiles, $templateCode, $templateParam)
    {
        // TODO: Implement multiSend() method.

    }
}